"""
API路由
"""
import logging
import os
from typing import List, Optional
from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, Query
from fastapi.responses import HTMLResponse
import uvicorn

from .models import (
    FileUploadResponse, FileListResponse, FileDetailResponse,
    SearchRequest, SearchResponse, BatchSearchRequest, BatchSearchResponse,
    SystemStatsResponse, SearchHistoryResponse, SearchStatsResponse,
    HealthCheckResponse, ErrorResponse
)
from ..core.file_manager import file_manager
from ..core.retriever import retriever
from ..core.vectorizer import vectorizer
from ..core.milvus_client import milvus_client
from ..config.database import db_manager
from ..config.settings import WEB_CONFIG

logger = logging.getLogger(__name__)

# 创建路由器
api_router = APIRouter(prefix="/api/v1", tags=["API"])

# 文件管理路由
@api_router.post("/files/upload", response_model=FileUploadResponse)
async def upload_file(file: UploadFile = File(...)):
    """上传文件"""
    try:
        # 保存上传的文件
        file_info = file_manager.save_uploaded_file(file)

        # 检查Milvus是否可用
        try:
            milvus_stats = milvus_client.get_collection_stats()
            milvus_available = milvus_stats is not None
        except:
            milvus_available = False

        # 如果Milvus不可用，只保存文件不进行向量化
        if not milvus_available:
            return FileUploadResponse(
                success=True,
                file_id=file_info["file_id"],
                filename=file_info["original_filename"],
                message="文件上传成功（Milvus不可用，未进行向量化）"
            )

        # 处理文件
        result = file_manager.process_file(file_info)

        if result["success"]:
            return FileUploadResponse(
                success=True,
                file_id=file_info["file_id"],
                filename=file_info["original_filename"],
                message="文件上传并处理成功"
            )
        else:
            return FileUploadResponse(
                success=False,
                error=result.get("error", "文件处理失败")
            )

    except Exception as e:
        logger.error(f"文件上传失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.get("/files", response_model=FileListResponse)
async def get_file_list(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页大小"),
    status: Optional[str] = Query(None, description="状态过滤"),
    file_type: Optional[str] = Query(None, description="文件类型过滤")
):
    """获取文件列表"""
    try:
        result = file_manager.get_file_list(page, page_size, status, file_type)
        return FileListResponse(**result)

    except Exception as e:
        logger.error(f"获取文件列表失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.get("/files/{file_id}", response_model=FileDetailResponse)
async def get_file_detail(file_id: str):
    """获取文件详情"""
    try:
        result = file_manager.get_file_detail(file_id)
        return FileDetailResponse(**result)

    except Exception as e:
        logger.error(f"获取文件详情失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.delete("/files/{file_id}")
async def delete_file(file_id: str):
    """删除文件"""
    try:
        result = file_manager.delete_file(file_id)

        if result["success"]:
            return {"success": True, "message": "文件删除成功"}
        else:
            raise HTTPException(status_code=400, detail=result.get("error", "删除失败"))

    except Exception as e:
        logger.error(f"删除文件失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# 搜索路由
@api_router.post("/search", response_model=SearchResponse)
async def search(request: SearchRequest):
    """搜索"""
    try:
        logger.info(f"收到搜索请求: query='{request.query}', top_k={request.top_k}")
        logger.debug(f"搜索请求详情: filter_expr={request.filter_expr}, user_id={request.user_id}, session_id={request.session_id}")

        # 检查是否跳过Milvus
        skip_milvus = os.getenv("SKIP_MILVUS", "false").lower() == "true"
        logger.debug(f"SKIP_MILVUS环境变量: {skip_milvus}")

        if skip_milvus:
            # 简化搜索：返回提示信息
            logger.info("跳过Milvus搜索，返回简化结果")
            return SearchResponse(
                success=True,
                query=request.query,
                results=[],
                total_found=0,
                total_returned=0,
                search_time=0.001,
                similarity_threshold=0.05,
                error="简化模式：向量检索功能不可用"
            )

        logger.info("开始执行检索器搜索")
        result = retriever.search(
            query=request.query,
            top_k=request.top_k,
            filter_expr=request.filter_expr,
            user_id=request.user_id,
            session_id=request.session_id
        )
        logger.info(f"检索器搜索完成: success={result['success']}, results_count={len(result.get('results', []))}")

        if result["success"]:
            response = SearchResponse(**result)
            # 如果是从数据库检索且Milvus不可用，添加提示信息
            if result.get("source") == "database" and not result.get("milvus_available", True):
                response.error = "注意：向量库不可用，当前使用数据库关键词检索，建议检查向量库服务"
            logger.info(f"返回搜索结果: total_found={response.total_found}, source={response.source}")
            return response
        else:
            logger.error(f"搜索失败: {result.get('error', '未知错误')}")
            raise HTTPException(status_code=400, detail=result.get("error", "搜索失败"))

    except Exception as e:
        logger.error(f"搜索失败: {e}")
        logger.exception(e)
        raise HTTPException(status_code=500, detail=str(e))

@api_router.post("/search/batch", response_model=BatchSearchResponse)
async def batch_search(request: BatchSearchRequest):
    """批量搜索"""
    try:
        results = retriever.batch_search(request.queries, request.top_k)
        return BatchSearchResponse(results=results)

    except Exception as e:
        logger.error(f"批量搜索失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.get("/search/history", response_model=SearchHistoryResponse)
async def get_search_history(
    user_id: Optional[str] = Query(None, description="用户ID"),
    limit: int = Query(100, ge=1, le=1000, description="返回数量限制")
):
    """获取检索历史"""
    try:
        history = retriever.get_search_history(user_id, limit)
        return SearchHistoryResponse(history=history)

    except Exception as e:
        logger.error(f"获取检索历史失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.get("/search/stats", response_model=SearchStatsResponse)
async def get_search_stats():
    """获取检索统计"""
    try:
        stats = retriever.get_search_stats()
        return SearchStatsResponse(**stats)

    except Exception as e:
        logger.error(f"获取检索统计失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# 系统管理路由
@api_router.get("/system/stats", response_model=SystemStatsResponse)
async def get_system_stats():
    """获取系统统计信息"""
    try:
        stats = file_manager.get_system_stats()

        # 添加缓存统计
        from ..utils.cache_manager import cache_manager
        cache_stats = cache_manager.get_stats()

        # 确保所有必需字段都存在
        response_data = {
            "files": stats.get("files", {"total": 0, "processed": 0, "failed": 0}),
            "vectors": stats.get("vectors", {"total_chunks": 0, "milvus_entities": 0}),
            "file_types": stats.get("file_types", []),
            "milvus": stats.get("milvus", {"status": "unknown"}),
            "cache": cache_stats
        }

        return SystemStatsResponse(**response_data)

    except Exception as e:
        logger.error(f"获取系统统计失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.get("/system/health", response_model=HealthCheckResponse)
async def health_check():
    """健康检查"""
    try:
        import time
        from .. import __version__

        # 检查各个服务状态
        services = {}

        # 检查数据库
        try:
            from sqlalchemy import text
            session = db_manager.get_session()
            session.execute(text("SELECT 1"))
            session.close()
            services["database"] = "healthy"
        except Exception as e:
            services["database"] = f"unhealthy: {str(e)}"

        # 检查Milvus
        try:
            stats = milvus_client.get_collection_stats()
            if stats:
                services["milvus"] = "healthy"
            else:
                services["milvus"] = "unhealthy"
        except Exception as e:
            services["milvus"] = f"unhealthy: {str(e)}"

        # 检查向量模型
        try:
            model_info = vectorizer.get_model_info()
            if model_info:
                services["vector_model"] = "healthy"
            else:
                services["vector_model"] = "unhealthy"
        except Exception as e:
            services["vector_model"] = f"unhealthy: {str(e)}"

        # 整体状态
        overall_status = "healthy" if all("healthy" in status for status in services.values()) else "unhealthy"

        return HealthCheckResponse(
            status=overall_status,
            timestamp=time.strftime("%Y-%m-%d %H:%M:%S"),
            version=__version__,
            services=services
        )

    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.post("/system/init")
async def initialize_system():
    """初始化系统"""
    try:
        # 创建数据库表
        db_manager.create_tables()

        # 创建Milvus集合
        milvus_client.create_collection()

        return {"success": True, "message": "系统初始化成功"}

    except Exception as e:
        logger.error(f"系统初始化失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.delete("/system/reset")
async def reset_system():
    """重置系统"""
    try:
        # 删除数据库表
        db_manager.drop_tables()

        # 删除Milvus集合
        milvus_client.drop_collection()

        # 清除缓存
        from ..utils.cache_manager import cache_manager
        cache_manager.clear_pattern("*")

        # 重新创建
        db_manager.create_tables()
        milvus_client.create_collection()

        return {"success": True, "message": "系统重置成功"}

    except Exception as e:
        logger.error(f"系统重置失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.post("/system/cache/clear")
async def clear_cache():
    """清除缓存"""
    try:
        from ..utils.cache_manager import cache_manager, vector_cache, file_cache

        # 清除所有缓存
        vector_cache.clear_embeddings()
        vector_cache.clear_search_results()
        file_cache.clear_all_file_cache()

        return {"success": True, "message": "缓存清除成功"}

    except Exception as e:
        logger.error(f"清除缓存失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@api_router.get("/system/cache/stats")
async def get_cache_stats():
    """获取缓存统计"""
    try:
        from ..utils.cache_manager import cache_manager
        stats = cache_manager.get_stats()
        return {"success": True, "stats": stats}

    except Exception as e:
        logger.error(f"获取缓存统计失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# 模型信息路由
@api_router.get("/models/info")
async def get_model_info():
    """获取模型信息"""
    try:
        vector_model_info = vectorizer.get_model_info()
        milvus_info = milvus_client.get_collection_stats()

        return {
            "vector_model": vector_model_info,
            "milvus": milvus_info
        }

    except Exception as e:
        logger.error(f"获取模型信息失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# 错误处理 - 移除，因为APIRouter不支持exception_handler
